package com.rcadmin.busi.logread.service;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rcadmin.busi.logread.dto.FileNode;
import com.rcadmin.busi.logread.dto.LogDirRequest;
import com.rcadmin.busi.logread.dto.LogDirResult;
import com.rcadmin.busi.logread.dto.LogReadRequest;
import com.rcadmin.busi.logread.dto.LogReadResult;

/**
 * 读取日志服务
 * 
 * @author tanson lam
 * @create 2016年9月6日
 */
public class LogReadService {

	private static final Logger logger = LoggerFactory
			.getLogger(LogReadService.class);

	/**
	 * 读取目录的文件节点
	 * 
	 * @param logDirRequest
	 * @return
	 * @throws IOException
	 */
	public static LogDirResult readDir(LogDirRequest logDirRequest)
			throws IOException {
		if (logDirRequest == null)
			throw new IllegalArgumentException("参数不能为空！");

		String logDir = logDirRequest.getLogDir();
		if (StringUtils.isEmpty(logDir))
			throw new IllegalArgumentException("目录路径不能为空！");

		File directory = new File(logDir);
		if (!directory.isDirectory())
			throw new IOException("logDir is not a directory." + logDir);

		List<FileNode> fileNodeList = FileNode.getChildNode(directory);
		return new LogDirResult(fileNodeList.toArray(new FileNode[fileNodeList
				.size()]));
	}

	/**
	 * 读取日志文件
	 * 
	 * @param logReadRequest
	 * @return
	 */
	public static LogReadResult readFile(LogReadRequest logReadRequest) {
		LogReadResult logReadResult = new LogReadResult();
		try {
			if (logReadRequest == null)
				throw new IllegalArgumentException("参数不能为空！");
			String filePath = logReadRequest.getFilePath();
			Long lastReadPosition = logReadRequest.getLastReadPosition();
			Long readLastMinLen = logReadRequest.getReadLastMinLen();
			Long readMaxLine = logReadRequest.getReadMaxLine();

			if (StringUtils.isEmpty(filePath))
				throw new IllegalArgumentException("文件路径不能为空！");
			File crunchifyFile = new File(filePath);
			if (!crunchifyFile.exists())
				throw new IllegalArgumentException("文件不存在，" + filePath + "！");

			long fileLength = crunchifyFile.length();
			boolean isFirstRead = false;
			if (lastReadPosition == 0) {
				lastReadPosition = fileLength > readLastMinLen ? fileLength
						- readLastMinLen : 0;
				isFirstRead = true;
			}
			if (fileLength > lastReadPosition) {
				StringBuffer sb = new StringBuffer();
				RandomAccessFile readWriteFileAccess = new RandomAccessFile(
						crunchifyFile, "r");
				readWriteFileAccess.seek(lastReadPosition);
				String readContent = null;
				int readLine = 0;
				while ((readContent = readWriteFileAccess.readLine()) != null) {
					readLine++;
					// 忽略第一行不完整的记录
					if (isFirstRead && readLine == 1)
						continue;
					sb.append(readContent).append("\n");

					if (!isFirstRead && readLine >= readMaxLine)
						break;
				} 
				lastReadPosition = readWriteFileAccess.getFilePointer();
				readWriteFileAccess.close();
				return new LogReadResult(lastReadPosition, fileLength,
						sb.toString());
			} else {
				logReadResult.failResult(-2, "文件没有变化");
			}

		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			logReadResult.failResult(-1, e.getMessage());
		}
		return logReadResult;
	}
}
